<?php
namespace Admin\Controller;

use function array_filter;
use function json_decode;
use function json_encode;
use function number_format;
use Think\Controller;

class MessageController extends Controller
{
    /**
     * 评论
     */
    public function index()
    {
        $order_id = I('get.order_id');
        $order = M('order')->where(['order_id' => $order_id])->find(); //查出订单信息

        if (empty($order)) {
            echo "<script>alert('订单号不存在或已失效');history.go(-1);</script>";
        }

        // 查询该订单是否已经评论过
        $message = M('message')->where(['order_id' => $order_id])->field(['id'])->find();
        if ($message) {
            echo "<script>alert('该订单已经评论过不能继续评论');history.go(-1);</script>";
            exit();
        }

        // 根据订单查出对应的菜谱信息
        $food = M('order_detail as o')->where(['order_id' => $order['id']])
            ->join('left join food_food as f on o.food_id = f.id')
            ->field('f.id,f.name,f.price,o.num')
            ->select();
        // 查出所有员工
        $member = M('member')->where("table_id like '%". $order['order_name'] ."%'")->find();
        $this->assign('order', $order);
        $this->assign('food', $food);
        $this->assign('member', $member);
        $this->display();
    }

    /**
     * 处理评论
     */
    public function store()
    {
        $input = $_POST;
        $input['food_message'] = array_filter($input['food_message']);

        //添加操作
        $data = [
            'member_id' => $input['member_id'],
            'member_message' => $input['memeber_messaage'],
            'content' => $input['content'],
            'fenshu' => $input['fenshu'],
            'fuwu_fen' => $input['fuwu_fen'],
            'chuancai_fen' => $input['chuancai_fen'],
            'caipin_fen' => $input['caipin_fen'],
            'food_message' => json_encode($input['food_message']),
            'created_at' => date('Y-m-d H:i:s'),
            'order_id' => $input['order_id']
        ];
        if (M('message')->data($data)->add()) {
            echo "<script>alert('评论成功');location.href='/'</script>";
        } else {
            echo "<script>alert('评论失败');history.go(-1);</script>";
        }
    }
}